package com.playball.lottery.frm.yhzx;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.R;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.customview.BallDTO;
import com.playball.lottery.customview.ShowCustomDialog;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.frm.buyhall.SsqxhActivity;
import com.playball.lottery.frm.buyhall.SsqxhlbActivity;
import com.playball.lottery.frm.hemai.HeMaiDetailActivity;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.util.Constants;
import com.playball.lottery.util.ConvertJsonToList;
import com.playball.lottery.util.Logger;
import com.playball.lottery.util.LotUtil;
import com.playball.lottery.util.PreferencesUtils;


/**
 * 追号记录
 * 
 * @author Administrator
 * 
 */
public class ZhRecordActivity extends ListActivity {

	@SuppressWarnings("unused")
	private ProgressDialog dialog;
	private View loadMoreView;
	private Button loadMoreButton;
	// result返回集
	private List<Map<String, Object>> rData;

	// page返回集
	private Map<String, Object> pData;
	// 彩种编号
	private String lotID = "0";
	// 显示页号
	private int pageNo = 1;
	private int pageSize = 10;
	// 是否有下一页
	private boolean nextPage;
	/** 记录总条数 */
	private int intTotalNum;
	private Handler handler = new Handler();

	private List<Map<String, Object>> recordList = new ArrayList<Map<String, Object>>();
	private PaginationAdapter adapter = new PaginationAdapter();

	private boolean change = true;
	
	private Button btn_Buy;
	private LinearLayout linLay;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.yhzx_zhrecord);
		titleBar();
		initView();

		loadMoreButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				loadMoreButton.setText("正在加载中..."); // 设置按钮文字
				handler.postDelayed(new Runnable() {

					public void run() {
						pageNo += 1;
						change = false;
						startZhRecordThread();
						loadMoreButton.setText("加载更多..."); // 恢复按钮文字
					}
				}, 20);

			}
		});
		
		btn_Buy.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				PreferencesUtils pUtil = new PreferencesUtils(ZhRecordActivity.this, Constants.PREFERENCES_NAME);
				Intent intent = new Intent();
				int ssq_size = pUtil.getInt("ssq_size", 0);
				if (ssq_size != 0) {
					ArrayList<BallDTO> list = new ArrayList<BallDTO>();
					for (int i = 0; i < ssq_size; i++) {
						BallDTO ball = new BallDTO();
						ball.setSsq_ball(pUtil.getString("ssq_ball" + i, ""));
						list.add(ball);
					}
					intent.putExtra("list_ssqdto", list);
					intent.putExtra("AllMoney", pUtil.getInt("ssq_allMoney", 0));
					intent.setClass(ZhRecordActivity.this, SsqxhlbActivity.class);
					Toast.makeText(ZhRecordActivity.this, R.string.this_is_the_last_time_you_save_the_number,
							Toast.LENGTH_SHORT).show();
				} else {
					intent.setClass(ZhRecordActivity.this, SsqxhActivity.class);
				}
				startActivity(intent);
			}
		});
		
	}

	public void onPause() {
		super.onPause();
		
	}

	class AsyncLoader extends AsyncTask<String, Integer, String> {// 继承AsyncTask
		ShowTipDialog showdialog = new ShowTipDialog();

		String action;

		// 1.准备运行
		protected void onPreExecute() {
			showdialog.showDialog(ZhRecordActivity.this);
		}

		// 2.正在后台运行
		@Override
		protected String doInBackground(String... paramsArr) {
			// 处理后台执行的任务，在后台线程执行
			String strResult = null;

			action = paramsArr[1];
			// 获取请求返回值
			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(paramsArr[0], UserID, action, getApplicationContext());
			// 获取请求返回值
			return strResult;
		}

		// 3.进度更新
		protected void onProgressUpdate(Integer... progress) {
		}

		// 4.完成后台任务
		protected void onPostExecute(String result) {
			if (result != null) {
				try {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					// 接下来的就是JSON对象的操作了
					if (Integer.parseInt(js.getString("Code")) == 0) {
						if (action.equals("112")) {
							rData = getData(result);
							showList();
							showdialog.closeDialog();
							if(recordList.size()==0)
							{
								ZhRecordActivity.this.getListView().setVisibility(View.GONE);
								linLay.setVisibility(View.VISIBLE);
							}
						}
					} else {
						Toast.makeText(ZhRecordActivity.this, js.getString("Data"), Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException ex) {
					// 异常处理代码
					Log.e("error", ex.toString());
				} finally {
					showdialog.closeDialog();
				}
			} else {
				Toast.makeText(ZhRecordActivity.this, getString(R.string.problem_01), Toast.LENGTH_LONG).show();
			}
		}

		// 5.完成后操作
		protected void onCancelled() {
		}

	}

	private void initView() {
		loadMoreView = getLayoutInflater().inflate(R.layout.loadmore, null);
		loadMoreButton = (Button) loadMoreView.findViewById(R.id.loadMoreButton);
		btn_Buy=(Button)findViewById(R.id.btn_Buy);
		linLay=(LinearLayout)findViewById(R.id.linLay);
	}

	
	public void startZhRecordThread() {
		AsyncLoader task = new AsyncLoader();

		String[] dyn = new String[2];
		JSONObject params = new JSONObject();
		try {
			params.put("LotID", lotID);
			params.put("PageNo", pageNo);
			params.put("PageSize", pageSize);
		} catch (JSONException ex) {
			// TODO Auto-generated catch block
			Log.e("error", ex.toString());
		}
		dyn[0] = params.toString();
		// 追号记录
		dyn[1] = "112";// 117
		task.execute(dyn);
	}

	private List<Map<String, Object>> getData(String strResult) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		try {
			JSONTokener jsonParser1 = new JSONTokener(strResult);
			JSONObject js1 = (JSONObject) jsonParser1.nextValue();
			if (!"".equals(js1.getString("Data"))) {
				String Count = String.valueOf(ConvertJsonToList.getMap(js1.getString("Data")).get("Count"));
				intTotalNum = Integer.parseInt(Count);
				list = ConvertJsonToList.getList(String.valueOf(ConvertJsonToList.getMap(js1.getString("Data")).get(
						"item")));
			} else {
				// 数据为空时为0
				intTotalNum = 0;
			}
		} catch (JSONException ex) {
			// 异常处理代码
			Log.e("error", ex.toString());
		}
		return list;
	}

	public void showList() {
		int maxPage = (intTotalNum % pageSize == 0) ? (intTotalNum / pageSize) : (intTotalNum / pageSize + 1);
		if (pageNo < maxPage) {
			nextPage = true;
		} else {
			nextPage = false;
		}
		
		Logger.e("nextPage", "=" + nextPage);
		
		// 判断是否有下一页
		if (nextPage) {
//			this.getListView().addFooterView(loadMoreView);
		} else {
			this.getListView().removeFooterView(loadMoreView);
		}
		
		if (rData != null) {
			rData = modifyData(rData);
			for (int i = 0; i < rData.size(); i++) {
//				adapter.addItem(rData.get(i));
				recordList.add(rData.get(i));
			}
		}
		if (change) {
			adapter.notifyDataSetChanged();
		} else {
			adapter.notifyDataSetChanged();
		}
		
		//默认listView显示,Linearlayout隐藏
		this.getListView().setVisibility(View.VISIBLE);
		linLay.setVisibility(View.GONE);
	}

	class PaginationAdapter extends BaseAdapter {

		public int getCount() {
			return recordList.size();
		}

		public Map<String, Object> getItem(int position) {
			return recordList.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View view, ViewGroup parent) {
			if (view == null) {
				view = getLayoutInflater().inflate(R.layout.yhzx_zhrecord_list, null);
			}

			// 彩种
			TextView tvLotName = (TextView) view.findViewById(R.id.yhzx_zhrecord_lotname);
			tvLotName.setText(recordList.get(position).get("LotName").toString());

			// 彩种icon
			ImageView imageView = (ImageView) view.findViewById(R.id.imageView1);
			imageView.setImageResource(LotUtil.getLotIconIDByName(recordList.get(position).get("LotName").toString()));

			// 发起时间
			TextView tvLaunchTime = (TextView) view.findViewById(R.id.yhzx_zhrecord_launchtime);
			String DateTime = recordList.get(position).get("DateTime").toString();
//			DateTime = DateTime.substring(0, DateTime.length() - 3);// "2013-09-09 13:14:15"
																	// to
																	// 2013-09-09
																	// 13:14
			tvLaunchTime.setText(DateTime);

			// 期号
			TextView tvIssue = (TextView) view.findViewById(R.id.yhzx_zhrecord_issuenum);
			tvIssue.setText(recordList.get(position).get("IssueNum").toString());

			// 投注金额
			// TextView tvMoney = (TextView)
			// view.findViewById(R.id.yhzx_zhrecord_amount);
			// tvMoney.setText(recordList.get(position).get("Money").toString());

			// 状态
			TextView tvState = (TextView) view.findViewById(R.id.yhzx_zhrecord_status);
			tvState.setText(recordList.get(position).get("State").toString());

			// 中奖金额
			TextView tvBuy = (TextView) view.findViewById(R.id.yhzx_zhrecord_finish);
			tvBuy.setText(""+recordList.get(position).get("BuyedIssueNum").toString());
			
			return view;
		}

		/**
		 * 添加数据列表顄1�7
		 * 
		 * @param newsitem
		 */
		public void addItem(Map<String, Object> map) {
			recordList.add(map);
		}
	}

	// 对返回数据进行修改
	public List<Map<String, Object>> modifyData(List<Map<String, Object>> data) {
		for (int i = data.size() - 1; i >= 0; i--) {
			String lotName = data.get(i).get("LotName").toString();
			String issue = data.get(i).get("IssueNum").toString();
			String money = data.get(i).get("Money").toString();
			issue += "期";
			money += "元";
			data.get(i).put("IssueNum", issue);
			data.get(i).put("Money", money);
			if (lotName.equals("江西时时彩")) {
				data.remove(i);
			}
		}
		return data;
	}

	@Override
	protected void onListItemClick(ListView list, View view, int position, long id) {
		// TODO Auto-generated method stub
		// 追号期数
		super.onListItemClick(list, view, position, id);
		Intent intent = new Intent(ZhRecordActivity.this, ZhDetailActivity.class);
		intent.putExtra("ChaseID", adapter.getItem(position).get("ID").toString());
		intent.putExtra("AllMoney", adapter.getItem(position).get("Money").toString());
		startActivity(intent);
	}

	// TitleBar标题栏
	public void titleBar() {
		// Title信息(返回+Title)
		TextView info = (TextView) findViewById(R.id.top_title_info);
		info.setText(R.string.zhrecord);
		TextView back = (TextView) findViewById(R.id.top_title_back);
		back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onKeyDown(KeyEvent.KEYCODE_BACK, null);
			}
		});
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		
		pageNo = 1;
		recordList.clear();
		this.getListView().removeFooterView(loadMoreView);
		this.getListView().addFooterView(loadMoreView);
		setListAdapter(adapter);
		startZhRecordThread();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			this.finish();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}

	};

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
	};
}